<template>
  <div class="emergency_box">
    <div class="emergency_top">
      <div class="emergency_title">成本分布</div>
    </div>
    <div v-if="tableDate&&tableDate.length>0" id="main" ref="echartsRef" class="echarts_div" />
    <div v-else class="echarts_noData">
      <svg-icon icon-class="暂无数据" />
    </div>
  </div>
</template>

<script>
import { costRatio } from '@/api/receivableAndPayable/receivableAndPayableManage/receivableBoard'
import Big from 'big.js' // big.js解决精度丢失问题
import { mapGetters } from 'vuex'
export default {
  name: 'LocationDistribution',
  computed: {
    ...mapGetters([
      'windowResizeTag'
    ])
  },
  watch: {
    windowResizeTag() {
      if (this.myChart) {
        this.$nextTick(() => {
          setTimeout(() => {
            this.drawLine()
          }, 500)
        })
      }
    }
  },
  data() {
    return {
      msg: 'fafa',
      tableDate: ['1'],
      myChart: undefined,
      timer: undefined,
      allNumber: 0,
      sumCost: 0
    }
  },
  mounted() {
    this.resetScale() // 重置缩放
    // this.drawLine()
    this.getList()
    this.timer = setInterval(() => {
      this.getList()
    }, this.$store.state.common.refreshFrequency * 1000)
  },
  beforeDestroy() {
    // 页面关闭清除定时器
    clearInterval(this.timer)
  },
  methods: {
    resetScale() {
      const scaleX = this.$refs.echartsRef.clientWidth / 797
      const scaleY = this.$refs.echartsRef.clientHeight / 250
      this.$refs.echartsRef.style.transform = 'scale(' + Math.min(scaleX, scaleY) + ')'
      this.$refs.echartsRef.style.transformOrigin = 'left'
      this.$refs.echartsRef.style.marginRight = -(797 * (1 - Math.min(scaleX, scaleY))) + 'px'
    },
    getList() {
      // clearInterval(this.timer)
      costRatio().then(res => {
        this.allNumber = this.sum(res.data.map(item => item.cost))
        this.tableDate = res.data
        this.sumCost = res.sumCost
        this.$nextTick(() => {
          this.drawLine()
        })
      })
    },
    sum(arr) {
      return arr.reduce(function(prev, curr) {
        return new Big(prev).plus(curr).toString()
      })
    },
    drawLine() {
      if (this.myChart) {
        this.$echarts.init(document.getElementById('main')).dispose()
      }
      this.myChart = this.$echarts.init(document.getElementById('main'))
      const arr = []
      const nameArray = []
      this.tableDate.forEach(item => {
        // arr.push(item.number)
        arr.push({
          value: (item.cost / this.allNumber * 100).toFixed(2),
          name: item.name + ',' + item.cost
        })
        nameArray.push(item.name)
      })
      this.myChart.setOption({
        title: {
          top: '28%',
          left: '29%',
          text: `{a|总成本(万元)}\n{b|${this.sumCost}}`,
          textStyle: {
            rich: {
              a: {
                color: '#4E5766',
                fontSize: 14
              },
              b: {
                lineHeight: 50,
                color: '#1C2029',
                fontSize: 20,
                fontWeight: 'bold',
                align: 'center'
              }
            }
          }
        },
        tooltip: {
          trigger: 'item'
        },
        // 右边信息面板
        legend: {
          orient: 'vertical',
          right: '6%',
          top: 'middle',
          itemHeight: 14,
          itemWidth: 27,
          itemGap: 16,
          formatter: name => {
            let params1 = name.split(',')[0]
            if (params1.length > 7) {
              params1 = params1.substr(0, 6) + '...'
            }
            const params2 = name.split(',')[1]
            const arr = [
              '{a|' + params1 + '}',
              '{b|' + params2 + '}'
            ]
            return arr.join('')
          },
          textStyle: {
            rich: {
              a: {
                color: '#000000',
                fontSize: 16,
                padding: [0, 20],
                width: 50
              },
              b: {
                align: 'right',
                fontSize: 18,
                width: 80
              }
            }
          }
        },
        // 设置饼状图每个颜色块的颜色
        color: ['#D94228', '#E7B980', '#3ECBC7', '#1593EA', '#836AA8', '#B96F8E'],
        // 牵引线
        series: [
          {
            type: 'pie',
            radius: ['45%', '60%'],
            center: ['35%', '40%'],
            avoidLabelOverlap: true,
            silent: true,
            itemStyle: {
              // borderRadius: 6,
              borderColor: '#fff',
              borderWidth: 1
            },
            label: {
              padding: [0, -100],
              formatter: function(e) {
                const {
                  data: { name, value }
                } = e
                const params1 = name.split(',')[0]
                if (params1.length > 7 && params1.slice(0, 6) != params1) {
                  return `{a|${params1.slice(0, 6)}...  }{a|${value}%}\n\n`
                } else {
                  return `{a|${params1}  }{a|${value}%}\n\n`
                }
              },
              rich: {
                a: { fontSize: 16, color: '#000000' }
              }
            },
            // emphasis: {
            //   label: {
            //     show: true,
            //     fontSize: '40',
            //     fontWeight: 'bold'
            //   }
            // },
            labelLine: {
              show: true, // 数据标签引导线
              // 牵引线长度
              length: 7,
              length2: 140,
              lineStyle: {
                width: 1,
                type: 'solid',
                color: '#D8D8D8'
              }
            },
            data: arr
          }
        ]
        // graphic: [
        //   // 在环形图中间显示总成本文字
        //   {
        //     type: 'text',
        //     left: '30%', // 调整为居中
        //     top: '30%', // 微调以适应环形图中心
        //     style: {
        //       text: `总成本(万元)`, // 显示总成本
        //       textAlign: 'center',
        //       fontSize: 14,
        //       fill: '#666666'
        //     }
        //   },
        //   // 在环形图下方显示具体数值（示例345）
        //   {
        //     type: 'text',
        //     left: '31%', // 居中
        //     top: '40%', // 调整位置至环形图下方
        //     style: {
        //       text: this.sumCost, // 这里应该是您想要显示的具体数值
        //       width: 100,
        //       align: 'center',
        //       fontSize: 16,
        //       fontWeight: 'bold',
        //       fill: '#333',
        //       rich: {
        //         content: {
        //           width: 100,
        //           align: 'center'
        //         }
        //       }
        //     }
        //   }
        // ]
      })
    }
  }
}
</script>

<style lang="less" scoped>
.emergency_box{
  width: 100%;
  height: 100%;
}

.emergency_top {
  display: flex;
  justify-content: space-between;
  height: 50px;

  .emergency_title {
    font-weight: bold;
    font-size: 20px;
    line-height: 34px;
    letter-spacing: -0.21px;
    color: #333333;
    padding-top: 16px;
    padding-left: 20px;
  }
}
.echarts_div{
  height: 100%;
  padding: 20px 0 20px 10px;
}

</style>
